package cn.hm.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;

import javax.jms.Queue;
import javax.jms.Topic;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/8/1 12:05
 */
@Configuration
@ConditionalOnClass(value = ActiveMQTopic.class)
public class ActiveMQConfig {

    @Value("${boot-queue}")
    private String queueName;

    @Value("${boot-topic}")
    private String topicName;

    @Value("${spring.activemq.user}")
    private String username;

    @Value("${spring.activemq.password}")
    private String password;

    @Value("${spring.activemq.broker-url}")
    private String brokerUrl;

    @Bean
    public Queue queue() {
        return new ActiveMQQueue(queueName);
    }

    @Bean
    public Topic topic() {
        return new ActiveMQTopic(topicName);
    }

    @Bean
    @Primary
    public ActiveMQConnectionFactory activeMQConnectionFactory() {
        return new ActiveMQConnectionFactory(username, password, brokerUrl);
    }

    //处理队列的监听工厂
    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerFactoryQueue(ActiveMQConnectionFactory factory) {

        DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory = new DefaultJmsListenerContainerFactory();
        defaultJmsListenerContainerFactory.setConnectionFactory(factory);
        defaultJmsListenerContainerFactory.setPubSubDomain(false);//代表队列
        return defaultJmsListenerContainerFactory;
    }

    //处理主题的监听工厂
    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerFactoryTopic(ActiveMQConnectionFactory factory) {
        DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory = new DefaultJmsListenerContainerFactory();
        defaultJmsListenerContainerFactory.setConnectionFactory(factory);
        defaultJmsListenerContainerFactory.setPubSubDomain(true);//代表主题
        return defaultJmsListenerContainerFactory;
    }

}
